package cn.maxhou.controller;

import cn.maxhou.entity.SysRole;
import cn.maxhou.entity.SysUser;
import cn.maxhou.service.SysRoleService;
import cn.maxhou.util.Constants;
import cn.maxhou.util.Page;
import com.alibaba.fastjson2.JSON;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/main/role")
public class RoleController extends BaseController{
    private static final Logger LOGGER= LoggerFactory.getLogger(RoleController.class);

    @Autowired
    private SysRoleService sysRoleService;

    @GetMapping("/list")
    public String list(Model model){
        Page<SysRole> page=null;
        try{
            //查询所有角色信息
            List<SysRole> roleList=sysRoleService.findAll();
            model.addAttribute("list",roleList);
        } catch (Exception e) {
            LOGGER.error("RoleController中的page方法执行发生的错误",e);
            throw new RuntimeException(e);
        }
        return "role/list";
    }

    @GetMapping("/save")
    public String save(Model model){
        //回显数据时需要sysUser,这里给个空对象避免出错
        model.addAttribute("SysRole",new SysRole());
        return "role/save";
    }

    @PostMapping("/save")
    public String doSave(SysRole sysRole) throws Exception {
        try{
            SysUser loginUser=session(Constants.SESSION_USER);
            if(sysRole.getId()==null){
                sysRole.setCreatedUserId(loginUser.getId());
                sysRole.setCreatedTime(new Date());
            }else {
                sysRole.setUpdatedUserId(loginUser.getId());
                sysRole.setUpdatedTime(new Date());
            }
            boolean ok=sysRoleService.saveOrUpdate(sysRole);
            if (ok){
                //保存成功,跳回列表页面
                return redirect("/main/role/list");
            }
        }catch (Exception e){
            LOGGER.error("RoleController中的doSave方法执行发生错误",e);
            throw new RuntimeException(e);
        }
        return "role/save";
    }

    @GetMapping("/edit")
    public String toEdit(@RequestParam("id")Long id,Model model){
        SysRole sysRole=null;
        try{
            sysRole =sysRoleService.findById(id);
            //回显数据时需要sysUser,这里给个空对象避免出错
            model.addAttribute("sysRole",sysRole);
        } catch (Exception e) {
            LOGGER.error("RoleController中的toEdit方法执行发生错误",e);
            throw new RuntimeException(e);
        }
        return "role/save";
    }

    @ResponseBody
    @GetMapping(value = "/{id}/view")
    public String ajaxView(@PathVariable("id") Long id) throws IOException {
        HashMap<String,Object> resultMap=new HashMap<String,Object>();
        SysRole sysRole=null;
        try{
            sysRole =sysRoleService.findById(id);
            if (sysRole!=null){
                resultMap.put("code",200);
                resultMap.put("data",sysRole);
            }else {
                resultMap.put("code",500);
            }
        } catch (Exception e) {
            LOGGER.error("RoleController中的view方法执行发生错误",e);
            throw new RuntimeException(e);
        }
        return JSON.toJSONString(resultMap);
    }

    @GetMapping("/del/{id}")
    @ResponseBody
    public Map del(@PathVariable("id") Long id, HttpServletResponse response) throws IOException {
        HashMap resultMap=new HashMap<String,Object>();
        int flag=0;
        try{
            flag =sysRoleService.deleteById(id);

            if (flag>0){
                resultMap.put("code",200);
                System.out.println("删除成功");
            }else {
                resultMap.put("code",500);
                resultMap.put("msg","删除失败");
            }

        } catch (Exception e) {
            LOGGER.error("RoleController中的view方法执行发生错误",e);
            throw new RuntimeException(e);
        }
        return resultMap;
    }

    @GetMapping("/codeExist")
    @ResponseBody
    public Map codeExist(@RequestParam String code){
        LOGGER.debug("检查角色code为={}的角色是否存在",code);
        HashMap<String,Object> resultMap=new HashMap<String,Object>();
        if (code.isEmpty()){
            resultMap.put("exist",0);
        }else {
            try{
                SysRole sysRole=sysRoleService.getByCode(code);
                if (sysRole!=null){
                    resultMap.put("exist",1);
                }else {
                    resultMap.put("exist",0);
                }
            }catch (Exception e){
                LOGGER.error("RoleController中的codeExist方法执行发生错误", e);
                resultMap.put("error", "出现异常,请联系管理员处理!");
            }
        }
        return resultMap;
    }
}
